package com.tanger.auth.authorization.service;

import cn.hutool.core.date.DateUtil;
import com.tanger.common.utils.StringUtil;
import com.tanger.common.wechat.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * oAuth服务
 *
 */
//@Service
public class OAuthServiceImp {

	private  final Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * wechat oauth url
	 */
	public static String OAUTH = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
	
	/**
	 * 通过oauth获取用户详细信息
	 */
	public static String GET_USER_INFO_OAUTH = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	/**
	 * 获取oauth网页认证的token
	 */
	public static String GET_ACCESS_TOKEN_OAUTH = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	
	/**
	 * 获取access_token
	 */
	public static String GET_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
	
	/**
	 * 获取osession_key
	 */
	public static String GET_SESSIONKEY = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";


	/**
	 * 获得Oauth认证的URL
	 * @param redirectUrl	跳转的url
	 * @param charset	字符集格式
	 * @param scope	OAUTH scope
	 * @return oauth url
	 */
	public static String getOauthUrl(String redirectUrl,String charset,String scope)throws Exception{
		String url = "";
		try {
			url = OAUTH
					.replace("APPID", ConstantWeChat.APPID)
					.replace("REDIRECT_URI",
							URLEncoder.encode(redirectUrl, charset))
					.replace("SCOPE", scope);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return url;
	}
	
	/**
	 * 获取Access_Token（oAuth认证,此access_token与基础支持的access_token不同）
	 * 
	 * @param code
	 *            用户授权后得到的code
	 * @return AccessTokenOAuth对象
	 */
	public static AccessTokenOAuth getOAuthAccessToken(String code)throws Exception {
		String url = GET_ACCESS_TOKEN_OAUTH
				.replace("APPID", ConstantWeChat.APPID)
				.replace("SECRET", ConstantWeChat.APPSECRET)
				.replace("CODE", code);
		//LogUtils.writePayLog("OAuthServiceImp", "微信支付授权", "AccessTokenOAuth","url="+url);
		JSONObject jsonObject = WeixinUtil.httpsRequest(url, "POST", null);
		AccessTokenOAuth accessTokenOAuth = null;
		//LogUtils.writePayLog("OAuthServiceImp", "微信支付授权", "AccessTokenOAuth","res="+jsonObject);
		if (null != jsonObject) {
			if (!jsonObject.isNull("errcode") && StringUtil.isNull(jsonObject.get("errcode"))
					&& jsonObject.get("errcode") != "0") {
				System.out.println("OAuthServiceImp   微信支付失败  AccessTokenOAuth  获取access_token失败 errcode:" +jsonObject.getInt("errcode") + "，errmsg:"+ jsonObject.getString("errmsg"));
			} else {
				accessTokenOAuth = new AccessTokenOAuth();
				accessTokenOAuth.setAccessToken(jsonObject
						.getString("access_token"));
				accessTokenOAuth.setExpiresIn(jsonObject.getInt("expires_in"));
				accessTokenOAuth.setRefreshToken(jsonObject
						.getString("refresh_token"));
				accessTokenOAuth.setOpenid(jsonObject.getString("openid"));
				accessTokenOAuth.setScope(jsonObject.getString("scope"));
			}
		}
		return accessTokenOAuth;
	}

	/**
	 * 通过oauth获取用户详细信息
	 * 
	 * @param token
	 * @param openid
	 * @return UserWeiXin对象
	 */
	public static UserWeiXin getUserInfoOauth(String token, String openid)throws Exception {
		UserWeiXin user = null;
		if (token != null) {

			String url = GET_USER_INFO_OAUTH.replace("ACCESS_TOKEN", token)
					.replace("OPENID", openid);

			JSONObject jsonObject = WeixinUtil.httpsRequest(url, "POST", null);

			if (null != jsonObject) {
				if (StringUtil.isNull(jsonObject.get("errcode"))
						&& jsonObject.get("errcode") != "0") {
					System.out.println("OAuthServiceImp+  微信支付失败+    getUserInfoOauth+  获取用户信息失败 errcode:"
							+ jsonObject.getInt("errcode") + "，errmsg:"
							+ jsonObject.getString("errmsg"));
					
				} else {
					user = new UserWeiXin();
					user.setOpenid(jsonObject.getString("openid"));
					user.setNickname(jsonObject.getString("nickname"));
					user.setHeadimgurl(jsonObject.getString("headimgurl"));
					user.setSex(jsonObject.getInt("sex"));
					user.setCity(jsonObject.getString("city"));
					user.setCountry(jsonObject.getString("country"));
					user.setProvince(jsonObject.getString("province"));
					user.setLanguage(jsonObject.getString("language"));
					user.setPrivilege(jsonObject.getString("privilege"));
				}
			}
		}
		return user;
	}
	
	/**
	 * 发送分享打赏信息
	 *
	 * @param openid
	 * @return UserWeiXin对象
	 */
	public static void sendMsgForReward(String openid,String userName,String money,String content,String title)throws Exception {

		String url = GET_ACCESS_TOKEN.replace("APPID", ConstantWeChat.APPID).replace("SECRET", ConstantWeChat.APPSECRET);
		JSONObject jsonObject = WeixinUtil.httpsRequest(url, "POST", null);
		
		String access_token=jsonObject.getString("access_token");
		
		String smsurl ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", access_token);
		
		JSONObject paramJson  = new JSONObject();
		paramJson.put("touser", openid);
		paramJson.put("template_id", "AdMBCRQJKWAMHYQh0T7ONz9WpMtSNvQx90kKHQDwDuQ");
		//paramJson.put("url", "http://weixin.qq.com/download");
		JSONObject dataJson = new JSONObject();
		
		JSONObject valJson  = new JSONObject();
		valJson.put("value", title);
		dataJson.put("first", valJson);
		
		valJson  = new JSONObject();
		valJson.put("value", userName);
		dataJson.put("keyword1", valJson);
		
		valJson  = new JSONObject();
		valJson.put("value", money);
		dataJson.put("keyword2", valJson);
		
		valJson  = new JSONObject();
		valJson.put("value", DateUtil.format(new Date(),"yyyy-MM-dd"));
		dataJson.put("keyword3", valJson);
		
		valJson  = new JSONObject();
		valJson.put("value", content);
		dataJson.put("remark", valJson);
		
		paramJson.put("data", dataJson);
		
		
		JSONObject dataJson1 = new JSONObject();
		JSONObject valJson1  = new JSONObject();
		valJson1.put("appid", "wx116d815e3d3e99f5");
		dataJson1.put("pagepath", "/pages/news/news");
		paramJson.put("miniprogram", dataJson1);
		
		JSONObject json = WeixinUtil.httpsRequest(smsurl, "POST",paramJson.toString());
		
		System.out.println(json);
	}
	

	public static String getSessionKeyBycode(String code) throws Exception {
		String requestUrl = GET_SESSIONKEY.replace("APPID", WxPayConfig.WECHAT_APP_ID).//填写自己的appid
		        replace("SECRET", WxPayConfig.WECHAT_APP_SECRET).replace("JSCODE", code);//填写自己的appsecret，
		JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "POST", null);
		return jsonObject.toString();
	}
	public static void main(String[] args) throws JSONException {
		try {

			System.out.println(getSessionKeyBycode("033WGEkl2rhvj74hPTnl2irNc32WGEkg"));
//			String encryptedData="J5OxBV9ZNHjQsj54n4A9vJjycKHe/U7g2W7h7RZPE1Cy86lDL7ZVRjW34tKSmPoXxCe9ljZgcrAqBY/Jo0FLYonpRt1noSZJWSVEeC8bR8fAo2xUvEZuD5H2ezxM1bcxTJy9+5T/o5zKUX6GVIUDuOuzaoCsrmo+HAzf4Fhv9o5U6ggOF2st8w2UyhhVkeqxhw5cSiS2LspMUzFbn/khag==";
//			String aeskey="IJTu4cs54tGo6PkY6w00ug==";
//			String iv="oW81eEBphOroJ2teY/HS/A==";

//
//		  String res = new String(CryptoUtil.decrypt(Base64.decodeStr(encryptedData),Base64.decodeStr(aeskey),Base64.decodeStr(iv), CryptoUtil.CryptType.AES_CBC_PKCS7));
//		  System.out.println(res);
//     	  System.out.println(WxUtils.wxDecrypt(encryptedData,aeskey,iv));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
